package com.newdjk.newdoctor.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ajguan.library.EasyRefreshLayout;
import com.ajguan.library.LoadModel;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.newdjk.newdoctor.BasActivity;
import com.newdjk.newdoctor.MyApplication;
import com.newdjk.newdoctor.R;
import com.newdjk.newdoctor.adapter.LetterAdapter;
import com.newdjk.newdoctor.adapter.PatientAdapter;
import com.newdjk.newdoctor.entity.DoctorPatientRelationEntity;
import com.newdjk.newdoctor.entity.InquiryRecordListDataEntity;
import com.newdjk.newdoctor.entity.PatientInfoEntity;
import com.newdjk.newdoctor.entity.PatientListEntity;
import com.newdjk.newdoctor.entity.PrescriptionMessageEntity;
import com.newdjk.newdoctor.net.BaseComPleteObserver;
import com.newdjk.newdoctor.net.NetServices;
import com.newdjk.newdoctor.utils.Contants;
import com.newdjk.newdoctor.utils.Event;
import com.newdjk.newdoctor.utils.LogUtils;
import com.newdjk.newdoctor.utils.RxBus;
import com.newdjk.newdoctor.utils.SpUtils;
import com.newdjk.newdoctor.view.ClearEditText;
import com.newdjk.newdoctor.view.MyLetterSortView;
import com.newdjk.okhttp.entity.BaseEntity;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 我得患者
 */
public class MyPatientActivity extends BasActivity {


    private static final String TAG = "MyPatientActivity";
    @BindView(R.id.mNodataContainer)
    RelativeLayout mNodataContainer;
    @BindView(R.id.message_recycler_view)
    RecyclerView messageRecyclerView;
    @BindView(R.id.easylayout)
    EasyRefreshLayout easylayout;
    @BindView(R.id.iv_no)
    ImageView ivNo;
    @BindView(R.id.fast_letter_keyindex)
    RecyclerView fastLetterKeyindex;
    @BindView(R.id.tv_choose)
    TextView tvChoose;
    @BindView(R.id.et_patient_msg)
    ClearEditText etPatientMsg;
    @BindView(R.id.im_clear)
    ImageView imClear;
    @BindView(R.id.mSearchContainer)
    LinearLayout mSearchContainer;
    @BindView(R.id.lv_grouping)
    LinearLayout lvGrouping;
    @BindView(R.id.group_help)
    LinearLayout groupHelp;
    @BindView(R.id.focus_patient)
    TextView focusPatient;
    @BindView(R.id.lv_focus_patient)
    LinearLayout lvFocusPatient;
    private int pageindex = 1;
    private List<PatientListEntity.ReturnDataBean> mPaintList = new ArrayList<>();
    private List<String> letterList = new ArrayList<>();
    private PatientAdapter mPatientAdapter;
    private String mPatientNameContent = "";

    private Gson mGson = new Gson();

    private Observable<Boolean> changeInfobservable;
    private LetterAdapter mLetterAdapter;

    @Override
    protected String setTitle() {
        return "患者";
    }

    @Override
    protected int initViewResId() {
        return R.layout.activity_patient;
    }


    @Override
    protected void initListener() {
        easylayout.addEasyEvent(new EasyRefreshLayout.EasyEvent() {
            @Override
            public void onLoadMore() {
                getPatientList();
            }

            @Override
            public void onRefreshing() {
                pageindex = 1;
                mPaintList.clear();
                letterList.clear();
                easylayout.setLoadMoreModel(LoadModel.COMMON_MODEL);
                getPatientList();
            }
        });


        etPatientMsg.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString())) {
                    imClear.setVisibility(View.GONE);
                } else {
                    imClear.setVisibility(View.VISIBLE);
                }
                pageindex = 1;
                mPaintList.clear();
                letterList.clear();
                mPatientNameContent = etPatientMsg.getText().toString().trim();
                getPatientList();
            }
        });

        imClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etPatientMsg.setText("");
            }
        });


        mPatientAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                //    ToastUtil.setToast("点击了" + mPaintList.get(position).getPatientName());


                Type jsonType = new TypeToken<PrescriptionMessageEntity<InquiryRecordListDataEntity>>() {
                }.getType();
                PatientInfoEntity PatientInfo = new PatientInfoEntity();

                //   PatientInfo.setBirthday(mDataList.get(position).getBirthday());
                String paName = mPaintList.get(position).getPatientName();
                if (TextUtils.isEmpty(paName)){
                    PatientInfo.setPatientName("");
                }else {
                    PatientInfo.setPatientName(paName.substring(2, paName.length()));
                }

                PatientInfo.setPatientId(mPaintList.get(position).getPatientId());
                PatientInfo.setPatientSex(mPaintList.get(position).getPatientSex());
                PatientInfo.setAge(String.valueOf(mPaintList.get(position).getAge()));
                DoctorPatientRelationEntity DoctorPatientRelation = new DoctorPatientRelationEntity();
                DoctorPatientRelation.setDrPatientId(mPaintList.get(position).getDrPatientId());
                InquiryRecordListDataEntity InquiryRecordListDataEntity = new InquiryRecordListDataEntity();
                InquiryRecordListDataEntity.setDoctorPatientRelation(DoctorPatientRelation);
                InquiryRecordListDataEntity.setPatientInfo(PatientInfo);
                //  LoginEntity LoginEntity = mGson.fromJson(SpUtils.getString(Contants.LoginJson), com.newdjk.doctor.ui.entity.LoginEntity.class);
                PrescriptionMessageEntity<InquiryRecordListDataEntity> prescriptionMessageEntity = mGson.fromJson(SpUtils.getString(Contants.LoginJson), jsonType);
                if (prescriptionMessageEntity != null) {
                    prescriptionMessageEntity.setPatient(InquiryRecordListDataEntity);
                    String json = mGson.toJson(prescriptionMessageEntity);
                    Intent ArchivesIntent = new Intent(MyPatientActivity.this, WebViewActivity.class);
                    ArchivesIntent.putExtra("prescriptionMessage", json);
                    ArchivesIntent.putExtra(Contants.TYPE, 4);
                    startActivity(ArchivesIntent);
                }
            }
        });
        mLetterAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                String s=letterList.get(position);
                if (s == "#") {
                    messageRecyclerView.scrollToPosition(0);
                } else {
                    for (int i = 0; i < mPaintList.size(); i++) {
                        String nameLetter = mPaintList.get(i).getNameLetter();
                        Log.d(TAG, "点击了" + s + "当前列表" + nameLetter + " 循环" + i);
                        if (!TextUtils.isEmpty(nameLetter)) {
                            if (s.equals(nameLetter.substring(0, 1))) {
                                messageRecyclerView.scrollToPosition(i);
                                Log.d(TAG, " 跳到" + i);
                                break;
                            } else {
                                continue;
                            }

                        }
                    }
                }
            }
        });


//        fastLetterKeyindex.setOnTouchingLetterChangedListener(new MyLetterSortView.OnTouchingLetterChangedListener() {
//
//            @Override
//            public void onTouchingLetterChanged(final String s) {
//                if (!TextUtils.isEmpty(s)) {
//                    tvChoose.setVisibility(View.VISIBLE);
//                    tvChoose.setText(s + "");
//                }
//
//                if (s == "#") {
//                    messageRecyclerView.scrollToPosition(0);
//                } else {
//                    for (int i = 0; i < mPaintList.size(); i++) {
//                        String nameLetter = mPaintList.get(i).getNameLetter();
//                        Log.d(TAG, "点击了" + s + "当前列表" + nameLetter + " 循环" + i);
//                        if (!TextUtils.isEmpty(nameLetter)) {
//                            if (s.equals(nameLetter.substring(0, 1))) {
//                                messageRecyclerView.scrollToPosition(i);
//                                Log.d(TAG, " 跳到" + i);
//                                break;
//                            } else {
//                                continue;
//                            }
//
//                        }
//                    }
//                }
//
//
//            }
//
//            @Override
//            public void onCancel() {
//                tvChoose.setVisibility(View.GONE);
//            }
//        });

        lvGrouping.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent groupPatientIntent = new Intent(MyPatientActivity.this, WebViewActivity.class);
                groupPatientIntent.putExtra(Contants.TYPE, 5);
                startActivity(groupPatientIntent);
            }
        });
        groupHelp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent groupPatientIntent = new Intent
//                (MyPatientActivity.this, NewlyBuildGroupActivity.class);
//                startActivity(groupPatientIntent);
                //// 1诊所，2医生，3诊所并且是医生,4，药房  0啥都不是  诊所无申请处方
                if (MyApplication.LoginEntity.getUser().getRoleType() == 4) {
                    Intent applyzuozhen = new Intent(MyPatientActivity.this, WebViewActivity.class);
                    applyzuozhen.putExtra(Contants.TYPE, 23);
                    startActivity(applyzuozhen);
                } else {
                    Intent applyzuozhen = new Intent(MyPatientActivity.this, WebViewActivity.class);
                    applyzuozhen.putExtra(Contants.TYPE, 22);
                    startActivity(applyzuozhen);
                }


            }

        });

        lvFocusPatient.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent applyzuozhen = new Intent(MyPatientActivity.this, WebViewActivity.class);
                applyzuozhen.putExtra(Contants.TYPE, 26);
                startActivity(applyzuozhen);
            }
        });
    }

    @Override
    protected void initData() {
        getPatientList();
    }

    @SuppressLint("CheckResult")
    @Override
    protected void initView() {
        mPatientAdapter = new PatientAdapter(mPaintList);
        changeInfobservable = RxBus.get().register(Event.Chaneg_patient_info);

        changeInfobservable.observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                LogUtils.d(TAG, "收到更新病人数据");
                pageindex = 1;
                mPaintList.clear();
                letterList.clear();
                easylayout.setLoadMoreModel(LoadModel.COMMON_MODEL);
                getPatientList();
            }
        });
        messageRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        messageRecyclerView.setAdapter(mPatientAdapter);



        mLetterAdapter = new LetterAdapter(letterList);
        fastLetterKeyindex.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        fastLetterKeyindex.setAdapter(mLetterAdapter);

    }

    @Override
    public boolean IsShowBackIcon() {
        return true;
    }

    /**
     * 完成
     */

    public void getPatientList() {

        NetServices.Factory.getService().QueryDoctorPatientPage(
                MyApplication.LoginEntity.getUser().getDoctorId(),
                "-1",
                "1",
                "-1",
                "-1",
                mPatientNameContent,
                pageindex,
                10

        ).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseComPleteObserver<PatientListEntity>(MyPatientActivity.this,false) {
                    @Override
                    protected void onSuccees(BaseEntity<PatientListEntity> t) throws Exception {

                        if (pageindex != 1) {
                            easylayout.loadMoreComplete();
                        } else {
                            easylayout.refreshComplete();
                        }
                        List<PatientListEntity.ReturnDataBean> returnlist = t.getData().getReturnData();
                        if (returnlist != null) {
                            if (returnlist.size() == 10) {  //还有数据
                                pageindex++;
                                mPaintList.addAll(returnlist);
                                mPatientAdapter.setDataList(mPaintList);
                                mPatientAdapter.setList(mPaintList);

                            } else if (returnlist.size() >= 0 && returnlist.size() < 10) { //加载完成
                                pageindex++;
                                mPaintList.addAll(returnlist);
                                mPatientAdapter.setDataList(mPaintList);
                                mPatientAdapter.setList(mPaintList);

                                easylayout.setLoadMoreModel(LoadModel.NONE);
                            }
                            reFreshNameLetter(returnlist);
                            mLetterAdapter.setNewInstance(letterList);
                            mLetterAdapter.notifyDataSetChanged();
                        }

                        if (mPaintList.size() <= 0) {
                            Log.i("MessageFragment", "lenError");
                            // mEasylayout.setVisibility(View.GONE);
                            messageRecyclerView.setVisibility(View.VISIBLE);
                            mNodataContainer.setVisibility(View.GONE);
                        } else {
                            //  mEasylayout.setVisibility(View.VISIBLE);
                            messageRecyclerView.setVisibility(View.VISIBLE);
                            mNodataContainer.setVisibility(View.GONE);
                        }


                    }

                    @Override
                    protected void onFailure(Throwable e, String erroressage, boolean isNetWorkError) throws Exception {
                        super.onFailure(e, erroressage, isNetWorkError);

                        easylayout.loadMoreFail();
                        if (mPaintList.size() <= 0) {
                            Log.i("MessageFragment", "lenError");
                            // mEasylayout.setVisibility(View.GONE);
                            messageRecyclerView.setVisibility(View.VISIBLE);
                            mNodataContainer.setVisibility(View.GONE);
                        } else {
                            //  mEasylayout.setVisibility(View.VISIBLE);
                            messageRecyclerView.setVisibility(View.VISIBLE);
                            mNodataContainer.setVisibility(View.GONE);
                        }

                    }
                });


    }

    private void reFreshNameLetter(List<PatientListEntity.ReturnDataBean> returnlist) {

        for (int i = 0; i < returnlist.size(); i++) {
            String nameLetter = returnlist.get(i).getNameLetter();
            if (TextUtils.isEmpty(nameLetter)) {
                nameLetter = "#";
                if (letterList.contains(nameLetter)) {
                    continue;
                } else {
                    letterList.add(nameLetter);
                }
            } else {
                nameLetter = nameLetter.substring(0, 1);
                if (letterList.contains(nameLetter)) {
                    continue;
                } else {
                    letterList.add(nameLetter);
                }
            }
        }

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.get().unregister(Event.Chaneg_patient_info, changeInfobservable);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
